﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SuperSocket;
using SuperWebSocket;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection.Emit;
using System.Windows.Interop;
namespace WpfLockScreen.Common
{
    public class SessionTool
    {
        public WebSocketSession Session { get; set; }
        public string Group { get; set; }
        public string ID { get; set; }

    }
    public class MsgInfo
    {
        /// <summary>
        /// 操作类型，1.向指定Group发送消息，2.向指定id发送消息，3.设置group 
        /// </summary>
        public string DoType { get; set; }
        /// <summary>
        /// 分组名
        /// </summary>
        public string GroupName { get; set; }
        /// <summary>
        /// 发送的数据
        /// </summary>
        public object Data { get; set; }
    }
    public partial class SocketServer
    {
        public SocketServer()
        {
            websocketServer();
        }
        //存储session和对应ip端口号的泛型集合
        private List<SessionTool> sessionList = new List<SessionTool>();
        private void websocketServer()
        {
            SuperWebSocket.WebSocketServer webSocketServer = new SuperWebSocket.WebSocketServer();
            webSocketServer.NewSessionConnected += WebSocketServer_NewSessionConnected;
            webSocketServer.NewMessageReceived += WebSocketServer_NewMessageReceived;
            webSocketServer.SessionClosed += WebSocketServer_SessionClosed;
            if (!webSocketServer.Setup("127.0.0.1", 5000))
            {

            }
            if (!webSocketServer.Start())
            {

            }
            //webSocketServer.Dispose();
        }
        /// <summary>
        /// 新客户端链接
        /// </summary>
        /// <param name="session"></param>
        private void WebSocketServer_NewSessionConnected(WebSocketSession session)
        {
            string ipAddress_Connect = session.RemoteEndPoint.ToString();
            
            sessionList.Add(new SessionTool() { ID = ipAddress_Connect, Session = session, Group = "" });
        }
        /// <summary>
        /// 收到消息处理
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param>
        private void WebSocketServer_NewMessageReceived(WebSocketSession session, string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                MsgInfo info = JsonConvert.DeserializeObject<MsgInfo>(value);
                if (info != null)
                {
                    switch (info.DoType)
                    {
                        case "SendGroup":
                            SendToGroup(info);
                            break;
                        case "SetGroup":
                            SetGroup(session, info);
                            break;
                        case "":
                            break;
                        case "SendAll":
                            SendToAll(session, info);
                            break;
                        default:
                            break;
                    }

                }
            }
        }
        /// <summary>
        /// 客户端关闭链接，集合中删除
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param>
        private void WebSocketServer_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
        {
            string ipAddress_Close = session.RemoteEndPoint.ToString();
            SessionTool tool = sessionList.Find(c => c.ID == ipAddress_Close);
            if (tool != null)
            {
                sessionList.Remove(tool);
            }
        }


        #region 封装处理

        /// <summary>
        ///    广播，同步推送消息给所有的客户端
        /// </summary>
        /// <param name="webSocketSession"></param>
        /// <param name="msg"></param>

        public  void SendToAll(WebSocketSession webSocketSession, MsgInfo info)
        {
            foreach (var item in webSocketSession.AppServer.GetAllSessions())
            {
              string senData=  JsonConvert.SerializeObject(info.Data);
                item.Send(senData);
            }
        }

        /// <summary>
        /// 向制定分组发送
        /// </summary>
        /// <param name="msgInfo"></param>
        public void SendToGroup(MsgInfo msgInfo)
        {
            List<SessionTool> tools = sessionList.FindAll(c => c.Group == msgInfo.GroupName);
            foreach (SessionTool item in tools)
            {
                string senData = JsonConvert.SerializeObject(msgInfo.Data);
                item.Session.Send(senData);
            }
        }

        /// <summary>
        /// 设置分组
        /// </summary>
        /// <param name="msgInfo"></param>
        public void SetGroup(WebSocketSession session, MsgInfo msgInfo)
        {
            string ipAddress_Close = session.RemoteEndPoint.ToString();
            SessionTool tool = sessionList.Find(c => c.ID == ipAddress_Close);
            if (tool != null)
            {
                tool.Group = msgInfo.GroupName;
            }

        }
        #endregion

    }

}